#import "liwuview.h"
#import "AFNetworking.h"
//#import "Config.h"
//#import "SBJson.h"
#import "liwucell.h"
#import "AppDelegate.h"
#import "UIView+LZCView.h"
#import "TCMsgHandler.h"
#import <Masonry.h>
#import "CustomADInputView.h"
#import <MBProgressHUD.h>
#import "FlyHorizontalFlowLauyout.h"


#define celll @"cell"

#import "PerWalletViewController.h"
#import "UIView+LZCView.h"

#define  _window_width  [UIScreen mainScreen].bounds.size.width
#define _window_height [UIScreen mainScreen].bounds.size.height

@interface liwuview ()<UICollectionViewDelegate,UICollectionViewDataSource>
{
    NSTimer *timer;
    int a;
	NSString *titleStr;
	NSString *contentStr;
	NSString *urlStr;
}
@end
@implementation liwuview
-(NSArray *)models{
    NSMutableArray *muatb = [NSMutableArray array];
    for (int i=0;i<self.allArray.count;i++) {
        liwuModel *model = [liwuModel modelWithDic:self.allArray[i]];
        [muatb addObject:model];
    }
    _models = muatb;
    return _models;
}

- (void)getUserInfo {
    
    [[NetworkTool sharedTool] requestWithName:@"获取用户信息" URLString:APIUser parameters:@{@"scope":@"wallet"} method:@"GET" callBack:^(id responseObject) {
//        NSDictionary *moneyDict = responseObject[@"data"];
//        int money = [moneyDict[@"money"] intValue] + [moneyDict[@"withdrawable_money"] intValue];
        _chongzhi.text = [NSString stringWithFormat:@"秀币 : %@", [responseObject[@"data"] valueForKey:@"coin"]];
        CGSize moneyTSize = [LZCTools textSizeWithText:_chongzhi.text font:_chongzhi.font];
        _chongzhi.frame = CGRectMake(10, 0, moneyTSize.width+20, _buttomView.height);
        
    }];

}

-(void)reloadColl{
    
    // GET /lives/gifts 获取所有礼物
    [[NetworkTool sharedTool] requestWithName:@"获取所有礼物" URLString:APIGifts parameters:nil method:@"GET" callBack:^(id responseObject) {
        
        self.allArray = responseObject[@"data"];
        //表格
        FlyHorizontalFlowLauyout *Flowlayout = [[FlyHorizontalFlowLauyout alloc] init];
        Flowlayout.minimumLineSpacing = 0;
        Flowlayout.minimumInteritemSpacing = 0;
        Flowlayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0, _window_width, _window_height/3- _window_height/18) collectionViewLayout:Flowlayout];
        Flowlayout.minimumLineSpacing = 0;
        Flowlayout.itemSize = CGSizeMake(_window_width/5, ( _window_height/3- _window_height/18)/2);
        self.collectionView.showsHorizontalScrollIndicator = NO;
        self.collectionView.pagingEnabled = YES;
        self.collectionView.scrollEnabled = YES;
        //self.collectionView.contentSize = CGSizeMake(_window_width*((self.allArray.count/10)+1), 0);
        
        //注册cell
        self.collectionView.backgroundColor = [UIColor clearColor];
        [self.collectionView registerClass:[liwucell class] forCellWithReuseIdentifier:celll];
        self.collectionView.dataSource = self;
        self.collectionView.delegate = self;
        self.collectionView.multipleTouchEnabled = NO;
        [self addSubview:self.collectionView];
        
        
        /*
        _scrollbuttom = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, _window_width, _window_height/3)];
        _scrollbuttom.contentSize = CGSizeMake(_window_width*((self.allArray.count/10)+1), 0);
        _scrollbuttom.pagingEnabled = YES;
        _scrollbuttom.showsHorizontalScrollIndicator = NO;
        _scrollbuttom.delegate = self;
        _scrollbuttom.bounces = NO;
        [_scrollbuttom addSubview:self.collectionView];
        [self addSubview:_scrollbuttom];
         */
        
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
        //底部条
        _buttomView = [[UIView alloc]initWithFrame:CGRectMake(0, _window_height/3- _window_height/18, _window_width,_window_height/18)];
        _buttomView.backgroundColor = [UIColor clearColor];
        _push = [UIButton buttonWithType:UIButtonTypeSystem];
        _push.backgroundColor = [UIColor lightGrayColor];
        //充值lable
        _chongzhi = [[UILabel alloc] init];
        _chongzhi.text = @"秀币 : 0";
//                        LiveUser *user = [Config myProfile];
//                        _chongzhi.text = [NSString stringWithFormat:@"充值 : %@",user.coin];
        _chongzhi.textColor = kWhiteColor;
        _chongzhi.font = [UIFont systemFontOfSize:14];
        CGSize moneyTSize = [LZCTools textSizeWithText:@"秀币 :" font:_chongzhi.font];
        _chongzhi.frame = CGRectMake(10, 0, moneyTSize.width+20, _buttomView.height);
        [_buttomView addSubview:_chongzhi];
        
        self.chargeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_buttomView addSubview:self.chargeBtn];
        [self.chargeBtn setTitle:@"充值" forState:UIControlStateNormal];
        [self.chargeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(moneyTSize.width+10, moneyTSize.height+6));
            make.left.mas_equalTo(_chongzhi.mas_right).offset(5);
            make.centerY.mas_equalTo(_buttomView.mas_centerY);
        }];
        self.chargeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        self.chargeBtn.layer.cornerRadius = self.chargeBtn.height/2;
        self.chargeBtn.layer.borderWidth = 1;
        self.chargeBtn.layer.borderColor = kWhiteColor.CGColor;
        self.chargeBtn.layer.masksToBounds = YES;
        [self.chargeBtn addTarget:self action:@selector(pushChargeClick:) forControlEvents:UIControlEventTouchUpInside];
        
        /*
        //充值上透明按钮
        _jumpRecharge = [[UIButton alloc] initWithFrame:CGRectMake(5,chongzhi_y,250,40)];
        _jumpRecharge.titleLabel.text = @"";
        [_jumpRecharge setBackgroundColor:[UIColor clearColor]];
        [_jumpRecharge addTarget:self action:@selector(DojumpRecharge) forControlEvents:UIControlEventTouchUpInside];
        [_buttomView addSubview:_jumpRecharge];
        //充值图标
        _coinImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"金币ios.png"]];
        int conimg_x = _chongzhi.frame.origin.x + _chongzhi.frame.size.width;
        _coinImg.frame = CGRectMake(conimg_x, chongzhi_y, 14, 14);
        [_buttomView addSubview:_coinImg];
        //箭头
        _jiantou = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"room_yingpiao_check"]];
        int jiantou_x = _coinImg.frame.origin.x + _coinImg.frame.size.width+4;
        _jiantou.frame = CGRectMake(jiantou_x, chongzhi_y, 14, 14);
        [_buttomView addSubview:_jiantou];
         */
        
        [_push setTitle:@"发送" forState:UIControlStateNormal];
        [_push setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_push addTarget:self action:@selector(doLiWu:) forControlEvents:UIControlEventTouchUpInside];
        _push.enabled = NO;
        _push.tag = 6789;
        _push.frame = CGRectMake(_window_width - 75,5,70,_buttomView.frame.size.height - 10);
        [_buttomView addSubview:_push];
        [self addSubview:_buttomView];
        
        UILabel *xianssss = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, _window_width, 1)];
        xianssss.backgroundColor = [UIColor lightGrayColor];
        [_buttomView addSubview:xianssss];
        
        CGFloat w = 80;
        
        _continuBTN = [UIButton buttonWithType:UIButtonTypeCustom];
        _continuBTN.frame = CGRectMake(_window_width - 80,self.frame.size.height - w - 5,w,w);
        _continuBTN.backgroundColor =  [UIColor colorWithRed:60/255.0 green:139/255.0 blue:126/255.0 alpha:1];
        [_continuBTN setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_continuBTN addTarget:self action:@selector(doLiWu:) forControlEvents:UIControlEventTouchUpInside];
        _continuBTN.tag = 5678;
        _continuBTN.titleLabel.numberOfLines = 2;
        _continuBTN.layer.masksToBounds = YES;
        _continuBTN.layer.cornerRadius = w/2;
        _continuBTN.hidden = YES;
        [_continuBTN setBackgroundImage:[UIImage imageNamed:@"bg_continue_send.png"] forState:UIControlStateNormal];
        [self addSubview:_continuBTN];
        
        
    }];

}

- (void)pushChargeClick:(UIButton *)sender {
    
    UIViewController *currVC = [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
    
    [currVC.navigationController pushViewController:[[PerWalletViewController alloc] init] animated:YES];
}


// 主页tableView是否滚动接收到通知
- (void)notificationXiuBi:(NSNotification *)notification {
    NSString *isR = notification.userInfo[@"xiubi"];
    NSLog(@"－－－－－充值秀币成功接收到通知------\n = %@", isR);
    _chongzhi.text = [NSString stringWithFormat:@"秀币 : %@", isR];
    CGSize moneyTSize = [LZCTools textSizeWithText:_chongzhi.text font:_chongzhi.font];
    _chongzhi.frame = CGRectMake(10, 0, moneyTSize.width+20, _buttomView.height);

    
}

//移除广播监听。
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


-(instancetype)initWithDic:(NSDictionary *)playdic andMyDic:(NSMutableArray *)myDic{
    self = [super init];
    if (self) {
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationXiuBi:) name:@"liveMoney" object:nil];
        
        self.models = [NSArray array];
        self.allArray = [NSArray array];
        self.pldic = playdic;
        self.mydic = myDic;
        [self reloadColl];
        [self getUserInfo];
        
        
        
    }
    return self;
}

- (void)hiddenGift {
    
    [UIView animateWithDuration:0.5 animations:^{
        self.frame = CGRectMake(0,SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT/3);
    }];
    
    for (UIView *obj in [[self superview] subviews]) {
        NSLog(@"++++++ %@", obj);
        // 获取父视图的子视图，宽是小图标的大小，那么就显示，其他私聊之类不显示
//        if (obj.width == 35) {
//            obj.hidden = NO;
//        }
        if (obj.tag == 10000) {
            obj.hidden = NO;
        }
    }
}

//发送礼物
-(void)doLiWu:(UIButton *)sender
{
    self.collectionView.userInteractionEnabled = NO;
    NSString *lianfa = @"y";
    _push.enabled = NO;
    _push.backgroundColor = [UIColor lightGrayColor];
    NSLog(@"发送了%@",_selectModel.giftname);
    NSString *giftType;
    //判断连发
    
    static int count = 0;
    int type;
    
    if ([_selectModel.type isEqualToString:@"0"]) {
        lianfa = @"n";
        _continuBTN.hidden = YES;
        _push.enabled = YES;
        _push.backgroundColor = [UIColor redColor];
        self.collectionView.userInteractionEnabled = YES;
        giftType = [NSString stringWithFormat:@"%@_%d", _selectModel.giftname, count];
        type = 0;
        [self hiddenGift];
    }
    else if([_selectModel.type isEqualToString:@"1"]){
        _continuBTN.hidden = NO;
        a = 30;
        if(timer == nil)
        {
            timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(jishiqi) userInfo:nil repeats:YES];
        }
        if(sender == _push)
        {
            [timer setFireDate:[NSDate date]];
        }
        giftType = _selectModel.giftname;
        type = 1;
    }
	else
	{
		_continuBTN.hidden = YES;
		_push.enabled = YES;
		_push.backgroundColor = [UIColor redColor];
		self.collectionView.userInteractionEnabled = YES;
		CustomADInputView *inputView = [[CustomADInputView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-300)/2, 200, 300, 181)];
		[inputView show];
		[inputView.sendBtn addActionWithblock:^{
			titleStr = inputView.titleText.text;
			contentStr = inputView.content.text;
			urlStr = inputView.url.text;
			if ([NSString isEmpty:titleStr] || [NSString isEmpty:contentStr] ||
				[NSString isEmpty:urlStr]) {
				
				//[self.viewController presentViewController:[LZCTools alertMessage:@"内容不可为空"] animated:YES completion:nil];
				MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:inputView animated:YES];
				HUD.label.text = @"内容不能为空";
				HUD.mode = MBProgressHUDModeText;
				[HUD hideAnimated:YES afterDelay:2.0];
				
				return;
			}
			else
			{
				NSString *uid = [GetUserDefaule(CURRLIVE) valueForKey:@"hostId"];
				NSDictionary *dict = @{
									   @"nums":@"1",
									   @"gift_id":_selectModel.ID,
									   @"title":titleStr,
									   @"content":contentStr,
									   @"url":urlStr,
									   };
				NSString *url = [NSString stringWithFormat:@"%@/%@/lives/gifts", APIUser, uid];
				[[NetworkTool sharedTool] requestWithName:@"发送礼物" URLString:url parameters:dict method:@"POST" callBack:^(id responseObject) {
					//        float money = [[responseObject[@"data"] valueForKey:@"money"] floatValue];
					//        _chongzhi.text = [NSString stringWithFormat:@"秀币 : %.2f", money/100];
					_chongzhi.text = [NSString stringWithFormat:@"秀币 : %@", [responseObject[@"data"] valueForKey:@"money"]];
					CGSize moneyTSize = [LZCTools textSizeWithText:_chongzhi.text font:_chongzhi.font];
					_chongzhi.frame = CGRectMake(10, 0, moneyTSize.width+20, _buttomView.height);
					[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
					[inputView removeFromSuperview];
				}];
			}
		}];
		//[self.viewController.view addSubview:inputView];
		return;
	}
    
    NSArray *idArr = @[@"9", @"19", @"21", @"22"];
    if ([idArr containsObject:_selectModel.ID]) {
        [self hiddenGift];
    }
    
    count++;
    
//    NSDictionary *userDict = GetUserDefaule(USERINFO);
    
    // POST /users/{uid}/lives/gifts 发送礼物 uid *收礼物者ID gift_id *礼物ID nums *数量
    NSString *uid = [GetUserDefaule(CURRLIVE) valueForKey:@"hostId"];
    NSDictionary *dict = @{@"nums":@"1",
                           @"gift_id":_selectModel.ID};
    NSString *url = [NSString stringWithFormat:@"%@/%@/lives/gifts", APIUser, uid];
    [[NetworkTool sharedTool] requestWithName:@"发送礼物" URLString:url parameters:dict method:@"POST" callBack:^(id responseObject) {
//        float money = [[responseObject[@"data"] valueForKey:@"money"] floatValue];
//        _chongzhi.text = [NSString stringWithFormat:@"秀币 : %.2f", money/100];
        _chongzhi.text = [NSString stringWithFormat:@"秀币 : %@", [responseObject[@"data"] valueForKey:@"money"]];
        CGSize moneyTSize = [LZCTools textSizeWithText:_chongzhi.text font:_chongzhi.font];
        _chongzhi.frame = CGRectMake(10, 0, moneyTSize.width+20, _buttomView.height);
    }];
	
}
//连发倒计时
-(void)jishiqi{
    [_continuBTN setTitle:[NSString stringWithFormat:@"连发\n  %d",a] forState:UIControlStateNormal];
    a-=1;
    if (a == 0) {
        [timer setFireDate:[NSDate distantFuture]];
        _push.backgroundColor = [UIColor redColor];
        _push.enabled = YES;
        _continuBTN.hidden = YES;
        self.collectionView.userInteractionEnabled = YES;
    }
}

-(void)chongzhiV:(NSString *)coins{
    
    _chongzhi.text = [NSString stringWithFormat:@"充值 : %@",coins];
    _chongzhi.font = [UIFont systemFontOfSize:14];
    int chongzhi_y = _buttomView.frame.size.height/2-7;
    CGSize size = [_chongzhi.text boundingRectWithSize:CGSizeMake(_window_width-100, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:_chongzhi.font} context:nil].size;
    _chongzhi.frame = CGRectMake(10, chongzhi_y, size.width, size.height);
    _coinImg.frame = CGRectMake(size.width + 14, chongzhi_y, 14, 14);
    int jiantou_x = _coinImg.frame.origin.x + _coinImg.frame.size.width+4;
    _jiantou.frame = CGRectMake(jiantou_x, chongzhi_y, 14, 14);
    _jumpRecharge.frame = CGRectMake(10, chongzhi_y, _chongzhi.frame.size.width + _coinImg.frame.size.width + _jiantou.frame.size.width + 10, 20);
    
}
//展示cell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.models.count;
}
//定义section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
    
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
        liwucell *cell = (liwucell *)[collectionView dequeueReusableCellWithReuseIdentifier:celll forIndexPath:indexPath];
        liwuModel *model = self.models[indexPath.item];
        cell.model = model;
        return cell;
}
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
        liwucell *cell = (liwucell *)[collectionView cellForItemAtIndexPath:indexPath];
        [collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
        _selectModel = self.models[indexPath.item];
        if (cell.duihao.hidden == NO) {
            cell.duihao.hidden = YES;
            _push.enabled = NO;
            _push.backgroundColor = [UIColor lightGrayColor];
        }
        else{
            _push.enabled = YES;
            _push.backgroundColor =[UIColor redColor];
            cell.duihao.hidden = NO;
        }
        cell.model = _selectModel;
        NSLog(@"选择%@",_selectModel.giftname);
    
}
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    
        liwucell *cell = (liwucell *)[collectionView cellForItemAtIndexPath:indexPath];
        cell.duihao.hidden = YES;
        _push.enabled = NO;
        _push.backgroundColor = [UIColor lightGrayColor];
  
}
//每个cell的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
        int cellWidth = _window_width/5;
        int cellHeight = ( _window_height/3- _window_height/18)/2;
        return CGSizeMake(cellWidth ,cellHeight);
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
        return UIEdgeInsetsMake(0,0,0,0);
}
//cell的最小行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
//cell的最小列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
//跳充值页面
-(void)DojumpRecharge{
    [self.giftDelegate jumpZuanShi];
}


@end
